﻿#region Copyright (C) Sector7 Software Studio. All rights reserved
/*******************************************************************************************
 * Creation
 *      Author:         Wolf Lai
 *      Date:           2012/2/1 19:16:52
 *      Version:        
 * Modification 
 *      Author: 
 *      Date: 
 *      Description: 
 *      Version:
 *******************************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sector7.Restaurant.APs.ServiceBus.Enums;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.Utility;
using Sector7.Restaurant.DAO;
using Sector7.Restaurant.DAO.OleDB;
using System.IO;
using Sector7.Restaurant.EntityType;

namespace Sector7.Restaurant.APs.ServiceBus.Utility
{
    /// <summary>
    /// 命令行工具类
    /// </summary>
    public class CommandLineUtil
    {
        #region Public functions
        /// <summary>
        /// 执行命令行
        /// </summary>
        /// <param name="commandLine">命令行</param>
        public static void Process(string commandLine)
        {
            CommandType commandType = CommandType.Unknown;

            string[] temps = commandLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (temps.Length > 0)
            {
                try
                {
                    commandType = (CommandType)Enum.Parse(typeof(CommandType), temps[0], true);
                }
                catch
                {
                    Console.WriteLine("ERR: Invalid command, please enter HELP to view more informations.");
                }

                switch (commandType)
                {
                    case CommandType.Initialize:
                        ProcessInitialize();
                        break;
                    case CommandType.ShutDown:
                        ProcessShutDown();
                        break;
                    case CommandType.Restart:
                        break;
                    case CommandType.Flag:
                        string[] args = null;
                        if (temps.Length > 1)
                        {
                            args = new string[temps.Length - 1];
                            Array.Copy(temps, 1, args, 0, temps.Length - 1);
                        }
                        ProcessFlag(args);
                        break;
                    case CommandType.Help:
                        ProcessHelp();
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion

        #region Private functions
        /// <summary>
        /// 执行初始化系统
        /// </summary>
        private static void ProcessInitialize()
        {
            int result = -1;

            Console.WriteLine("Whole system has not be initialized yet, there will do auto initialization next, please wait...");
            Console.WriteLine();

            Console.WriteLine(" - Prepare environment starting...");
            Console.WriteLine("\tRESULT: SUCCESS.");

            Console.WriteLine(" - Config IP address to default factor...");
            Console.WriteLine("\tRESULT: SUCCESS.");

            Console.WriteLine(" - Initialize database starting...");

            try
            {
                IDatabaseDAO db = new DatabaseDAO();
                StringBuilder sb = new StringBuilder();

                string configPath = DirectoryUtil.GenerateDirectoryPath(ApplicationUtil.GetBaseDirectory(), "Config");
                DirectoryInfo dir = new DirectoryInfo(configPath);

                StreamReader reader = null;
                foreach (FileInfo file in dir.GetFiles("*.sql"))
                {
                    reader = new StreamReader(string.Format(@"{0}\{1}", configPath, "DefaultTable.sql"));
                    while (!reader.EndOfStream)
                    {
                        sb.AppendLine(reader.ReadLine());
                    }
                    result = db.CreateTable(sb.ToString());

                    reader.Close();
                    reader.Dispose();
                }

                Console.WriteLine("\tRESULT: {0}.", result == 1 ? "Success" : "Failure");

                Console.WriteLine(" - Insert factory default data starting...");

                result = 0;

                S7_Company company = new S7_Company();
                company.UniqueId = "00000000-0000-0000-0000-000000000000";
                company.Address = "四川省射洪县武安河11号";
                company.Introduce = "可以喝汤的冒菜";
                company.Name = "赖家冒菜";
                company.Postcode = "629200";
                company.Telephone = "13778743510";
                ICompanyDAO companyDAO = new CompanyDAO();
                result += Convert.ToInt32(companyDAO.Create(company));

                RS_EmployeeGroup employeeGroup = new RS_EmployeeGroup();
                employeeGroup.GroupName = "系统内置用户组";
                employeeGroup.BonusRate = 0;
                employeeGroup.Permission = 999;
                IEmployeeGroupDAO employeeGroupDAO = new EmployeeGroupDAO();
                result += employeeGroupDAO.Create(employeeGroup);

                RS_Employee employee = new RS_Employee();
                employee.FirstName = "贝克汉姆";
                employee.LastName = "大卫";
                employee.Birthday = new DateTime(1975, 5, 2);
                employee.UserName = "beckham";
                employee.Password = "777";
                employee.MobilePhone = "0000000000000000";
                employee.Telephone = "0000000000000000";
                employee.PersonalId = "000000000000000000";
                employee.Gender = "Male";
                employee.Residence = "伦敦雷顿斯通";
                employee.Address = "美国洛杉矶";
                employee.GroupId = 1;
                employee.IsValid = true;
                employee.BasicSalary = 0;
                IEmployeeDAO employeeDAO = new EmployeeDAO();
                result += (int)employeeDAO.Create(employee);

                RS_Room hall = new RS_Room();
                hall.RoomName = "大厅";
                hall.RoomType = 0;
                IRoomDAO roomDAO = new RoomDAO();
                result += roomDAO.Create(hall);
            }
            catch (Exception e)
            {
                Logger.WriteLine(LogSeverityType.ERR, e);

                result = -1;
                Console.WriteLine("\tRESULT: {0}.", result == 4 ? "Success" : "Failure");
            }

            Console.WriteLine("System initialize done, there will restart now...");
        }

        /// <summary>
        /// 执行关闭
        /// </summary>
        private static void ProcessShutDown()
        {
            Console.WriteLine("ServiceBus is shutdown, please wait...");
            Logger.WriteLine(LogSeverityType.INF, "ServiceBus shutdown.");
            Environment.Exit(0);
        }

        /// <summary>
        /// 执行帮助
        /// </summary>
        private static unsafe void ProcessHelp()
        {
            Console.WriteLine("Display a list of ServiceBus supported commands.");
            Console.WriteLine();
            Console.WriteLine("  SHUTDONW	Shutdown the ServiceBus.");
            Console.WriteLine("  RESTART	Restart the ServiceBus.");
            Console.WriteLine("  FLAG		Set special flag of ServiceBus.");
            Console.WriteLine("  HELP		Display a list of ServiceBus supported commands.");
            Console.WriteLine();

            //var message = new Sector7.Framework.Structs.MulticastMessage();
            //message.MessageId = (int)MessageId.SalesBillAdded;
            //message.Timestamp = DateTime.Now.Ticks;
            //ConvertUtil.StringToBytePoint("192.168.1.101", message.Data);

            //Environments.SendBroadcast(message);
        }

        /// <summary>
        /// 执行标志设置
        /// </summary>
        /// <param name="args">命令参数</param>
        private static void ProcessFlag(params string[] args)
        {
            if (args == null)
            {
                Console.Write("Please input id or name: ");
                string tempKey = Console.ReadLine();
                Console.Write("Please input value: ");
                string tempValue = Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Display a list of all flags.");
                Console.WriteLine();
                Console.WriteLine("  1 - SHUTDONW [B]	Shutdown the ServiceBus.");
                Console.WriteLine("  2 - RESTART [B]	Restart the ServiceBus.");
                Console.WriteLine("  3 - FLAG [B]		Set special flag of ServiceBus.");
                Console.WriteLine("  4 - HELP [B]		Display a list of ServiceBus supported commands.");
                Console.WriteLine();
            }
        }
        #endregion
    }
}
